package sdp;

import java.lang.Math;

/** Immutable 2D Vector class. */
public class Vector2 {
	private double x;
	private double y;
	
	/// Create a new vector with given coordinates.
	public Vector2( double x, double y ) {
		this.x = x;
		this.y = y;
	}
	
	/// Get the X coordinate of this vector.
	public double getX() {
		return x;
	}
	
	/// Get the Y coordinate of this coordinate.
	public double getY() {
		return y;
	}
	
	/// Compute the norm of the vector.
	public double computeNorm() {
		return Math.sqrt( computeSquaredNorm() );
	}
	
	/// Compute the square of the vector's norm.
	public double computeSquaredNorm() {
		return x * x + y * y;
	}
	
	/// Subtract another vector from this one.
	public Vector2 minus( Vector2 rhs ) {
		return new Vector2( x - rhs.getX(), y - rhs.getY() );
	}
	
	/// Add another vector to this one.
	public Vector2 plus( Vector2 rhs ) {
		return new Vector2( x + rhs.getX(), y + rhs.getY() );
	}
	
	/// Multiply this vector by a scalar.
	public Vector2 times( double scalar ) {
		return new Vector2( x * scalar, y * scalar );
	}
	
	/// Check whether this vector is equal to another one within a given tolerance.
	public boolean approxEquals( Vector2 rhs, double tolerance ) {
		assert rhs != null;
		return  Math.abs( x - rhs.getX() ) <= tolerance &&
				Math.abs( y - rhs.getY() ) <= tolerance;
	}
}
